package com.antler.smt.portal.controller;

import com.antler.smt.entity.AttachmentEntity;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.AttachmentInfoMapper;
import com.antler.smt.response.base.Result;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *  TODO
 *
 *  @author vic
 *  @date 2018-03-25 22:05
 *  
 */
@RestController
@RequestMapping(value = "/upload")
@Api(description = "文件上传接口")
public class UploadController {

    /**
     * 附件
     */
    @Autowired
    private AttachmentInfoMapper attachmentInfoMapper;
    
    /**
     * 多文件上传
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/multifileUpload")
    @ApiOperation(value = "文件上传，支持多文件，以fileName命名，将文件放在请求流中", httpMethod = "POST")
    public Result multifileUpload(HttpServletRequest request) throws Exception {
        
        String filePath = System.getProperty("catalina.home") + "/webapps/uploadfile/";
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");
        List<String> saveFileNames = new ArrayList<>();
        List<Long> attachmentIds = new ArrayList<>();
        Result result = null;
        if (files.isEmpty()) {
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        } else {

            for (MultipartFile file : files) {
                String newFileName = Long.toString(DateUtil.dateToStamp(new Date()));
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                newFileName = newFileName + "." + suffix;
                saveFileNames.add(newFileName);
                AttachmentEntity entity = new AttachmentEntity();
                entity.setFileName(newFileName);
                entity.setCreateTime(new Date());
                entity.setUpdateTime(new Date());
                attachmentInfoMapper.insertSelectiveAndGetId(entity);
                long attachId = entity.getId();
                attachmentIds.add(attachId);
            }
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        FileUtil.upload(request, filePath, saveFileNames);
        result.setData(attachmentIds);
        return result;
    }

}
